package com.csc.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.csc.dao.SystemAccountDAO;
import com.csc.domain.SystemAccount;

import constants.Constant;

@Service
public class CustomUserDetailService implements UserDetailsService {

	@Autowired
	private SystemAccountDAO sysAccDAO;

	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		try {
			SystemAccount usr = sysAccDAO.getAccountByLoginId(userName);
			if (usr.getSystemStatus().getStatusId() == Constant.STATUS_ID_ACTIVE
					|| usr.getSystemStatus().getStatusId() == Constant.STATUS_ID_PREACTIVE) {
				boolean enabled = true;
				boolean accountNonExpired = true;
				boolean credentialsNonExpired = true;
				boolean accountNonLocked = true;
				return new User(usr.getAccountLoginId(),
						usr.getAccountPassword(), enabled, accountNonExpired,
						credentialsNonExpired, accountNonLocked,
						getAuthorities(usr.getSystemAccountType().getTypeId()));
			} else {
				return null;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;
	}

	public Collection<? extends GrantedAuthority> getAuthorities(int role) {
		List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
		return authList;
	}

	public List<String> getRoles(int role) {
		List<String> roles = new ArrayList<String>();
		if (role == Constant.ACCOUNT_TYPE_USER_ADMIN
				|| role == Constant.ACCOUNT_TYPE_USER_SUPPORT
				|| role == Constant.ACCOUNT_TYPE_USER_SYSTEM) {
			roles.add("ROLE_ADMIN");
		} else {
			roles.add("ROLE_USER");
		}
		return roles;
	}

	public static List<GrantedAuthority> getGrantedAuthorities(
			List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String role : roles) {
			authorities.add(new GrantedAuthorityImpl(role));
		}
		return authorities;
	}

}
